package com.cgx.tablet.beeper.api;

import android.support.annotation.NonNull;

import com.cgx.tablet.beeper.MyApplication;
import com.cgx.tablet.beeper.utils.AndroidUtil;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 自定义拦截器 为每个请求添加header(当前设备的唯一标识)
 * Created by cgx on 2018/9/17.
 */

public class CustomInterceptor implements Interceptor {

    @Override
    public Response intercept(@NonNull Chain chain) throws IOException {
        Request originalRequest = chain.request().newBuilder()
                .addHeader("client_id", AndroidUtil.getIpAddress(MyApplication.getGlobalContext()))
                .addHeader("accept", "application/json")
                .build();

        Response originalResponse = chain.proceed(originalRequest);
//        String bodyString = originalResponse.body().string();
//        try {
//            JSONObject jsonObject = new JSONObject(bodyString);
//            if (jsonObject.optString("code").contains("sesstion")){
//                //同步请求方式，自动登录
////                Log.d(TAG, "newSession:" + newSession);
//
//
//                //使用新的Token，创建新的请求
//                String newUrl = chain.request().url().toString();
//                Request newRequest = chain.request().newBuilder().url(newUrl).build();
//                Response newResponse = chain.proceed(newRequest);
//
//                String newBodyString = newResponse.body().string();
//                //重新请求
//                return newResponse.newBuilder()
//                        .body(ResponseBody.create(newResponse.body().contentType(), newBodyString))
//                        .build();
//            }
//
//            return originalResponse.newBuilder()
//                    .body(ResponseBody.create(originalResponse.body().contentType(), bodyString))
//                    .build();
//        } catch (JSONException e) {
//            e.printStackTrace();
//        }
        return originalResponse;
    }

//    private void login(){
//        String account = SharedPreferenceUtil.getAccount(MyApplication.getGlobalContext());
//        String password = SharedPreferenceUtil.getPassword(MyApplication.getGlobalContext());
//        Call<MsgResponse> call = ApiUtil.apiService.login(account, password);
//        MsgResponse loginResponse = call.execute().body();
//    }

}
